<?php


namespace app\admin\model;

use app\admin\authentication\Jwt as FirebaseJwt;
use app\lib\exception\admin\{
    SQLException,
    ErrorsException
};
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
class Admin extends Base
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

     public static function AdminUser($username,$password){
        $where = [
            'username' => $username,
            'password' => md5($password),
        ];
        //查询用户是否存在
        $user_data = self::field('id as uid,nickname,image,logintime,status')
            ->where($where)
            ->find();

        if(empty($user_data)){
            throw new SQLException([
                'code' => 404,
                'msg'  => '用户名或密码错误',
                'error_code' => 40004
            ]);
        }

         if($user_data['status'] == 1){
             //用户uid 后续使用
             $uid = $user_data['uid'];
             //更新登录IP和登录时间
             self::where('id', '=',$uid)
                 ->update(['logintime' => time(), 'loginip' => Request::ip()]);
             //查找规则
             $rules = Db::name('auth_group_access')
                 ->alias('a')
                 ->leftJoin('auth_group ag', 'a.group_id = ag.id')
                 ->field('a.group_id,ag.rules,ag.title')
                 ->where('uid', $uid)
                 ->find();
             //查询所有不验证的方法并放入规则中
             $authOpen = AuthRule::where('auth_open', '=', '0')
                 ->select();
             //获取AuthRule 信息
             $authRole = AuthRule::select();
             $authOpens = [];
             foreach ($authOpen as $k => $v) {
                 $authOpens[] = $v['id'];
                 //查询所有下级权限
                 $ids = getChildsRule($authRole, $v['id']);
                 foreach ($ids as $kk => $vv) {
                     $authOpens[] = $vv['id'];
                 }
             }
             $authOpensStr = !empty($authOpens) ? implode(",", $authOpens) : '';

             $rules['rules'] = $rules['rules'] . $authOpensStr;
             //重新查询要赋值的数据[原因是toArray必须保证find的数据不为空，为空就报错]
             $result = self::where(['username' => $username, 'password' => md5($password)])->find();
             //jwt 获取token
             $getJwtToken = (new FirebaseJwt())->getJwtToken($result,$rules['rules']);
             Cache::set('token'.$uid,$getJwtToken,360);
             if(empty($getJwtToken)){
                 throw new ErrorsException([
                     'code' => 404,
                     'msg'  => '获取token失败',
                     'error_code' => 40004
                 ]);
             }
             return $getJwtToken;
         }else{
             throw new SQLException([
                 'code' => 404,
                 'msg'  => '用户被禁用',
                 'error_code' => 40004
             ]);
         }
     }
}